/*
 * @Description: 保存待发
 */
import sendCommon from '@/handles/common/send';
import { APPLICATIONCATEGORYE } from '@/utils/const';
import globalMethods from '@/plugins/methods';
import globalData from "@/plugins/data";
import {fireEvent, getCollEventParams} from "@/handles/common/sdk";
import {useBaseInfoStore} from "@/store/modules/base-info";
import emitter from "@/utils/emitter";
import errHandle from "@/handles/common/err-handle";

/**
 * @description: 保存待发操作
 * @param {Object}colMainData 协同主数据
 */
async function saveDraft(resolve) {
  //提取参数
  const { useBaseInfo } = sendCommon;
  let { currentTemplateId, id } = useBaseInfo.baseInfo.collaborationSubmitData.colMainData;
  // 标题 由于绑定的是useBaseInfo.formInfo.subject 不要使用seBaseInfo.baseInfo.subject.value
  let subject = useBaseInfo.formInfo.subject.value;
  //获取正文iframe对象
  const fnx = sendCommon.useTemplate.zwIframe.contentWindow;
  //如果正文iframe对象不存在 则直接返回
  if (!fnx) {
    globalMethods.message.error($.i18n('collaboration.common.content.loading.js')); //正文未加载完成，请稍后重试
    return resolve();
  }
  //校验密级 标题 流程
  if (!useBaseInfo.checkSecret() || !useBaseInfo.validateSubject() || !useBaseInfo.validateAttachmentUploading()) return resolve();
  //流程模版是否进行了加签
  const isTemplate = currentTemplateId && currentTemplateId !== "0" && currentTemplateId !== "-1";
  if(useBaseInfo.hasAddNode && isTemplate && !confirm($.i18n("collaboration.newcoll.changeProcess.saveDraftConfirm.js"))) {
    return resolve();
  }
  //设置正文id信息
  fnx.contentAPI.setSaveContentParam(id, subject, currentTemplateId || '');
  //保存正文&流程图生成相关
  let cap4 = useBaseInfo.baseInfo.zwIframe.isCap4;
  if (!cap4) { 
    //用于快速选人生成流程图信息
    await emitter.publish("sendFreeCol");
    //保存正文
    let promise = await new Promise((resolveCallBack) => {
      const {id} = useBaseInfo.baseInfo.businessData.summary;
      // eslint-disable-next-line no-undef
      if (fnx.document) {
        fnx.document.getElementById("moduleId").value=id
        fnx.document.getElementById("id").value=''
      }
      fnx.contentAPI.submit({
        checkNull: false,
        mainbodyDomains: [],
        needCheckRepeatData: false,
        needCheckRule: false,
        needSn: false,
        needSubmit: true,
        optType: 'send',
        summaryId: id,
        failed: () => resolveCallBack(false),
        success: () => resolveCallBack(true),
      })
    });
    if (promise === false) {
      return resolve();
    }
  }
  

  sendCommon.confirmWorkflowStartDepartment(resolve,  function () {
      const businessData = useBaseInfoStore().baseInfo?.businessData || {};
      const eventParams = getCollEventParams(businessData, globalData);
    fireEvent('beforeSaveDraftColl', eventParams)
        .then(result=>{
            if (result===true){
                sendCommon
                    .waitSave()
                    .then(
                        (res) => {
                            switch (res.code) {
                                case 413:
                                  errHandle(
                                    res.data,
                                    (...arg) => {
                                      console.log('action, data ', arg);
                                      const [result] = arg || [];
                                      if (!result) return;
                                      //工作流事件弱校验
                                      if (result.workflowEvent){
                                        this.saveDraft(resolve);
                                        return;
                                      }
                                      if (!result.isCwp) return;
                                      //表单弱校验
                                      this.useBaseInfo.needCheckRule = false;
                                      this.saveDraft(resolve);
                                    },
                                    (err) => {
                                      console.log('send error', err);
                                    }
                                  );
                                    break;
                                default:
                                    globalMethods.message.success({
                                      content: $.i18n('collaboration.newColl.savePendingOk'),
                                      duration: 0.5,
                                      onClose() {
                                        let { COLLABORATION, CLO_PATH } = APPLICATIONCATEGORYE;
                                        let { summaryId, affairId } = res.data[COLLABORATION];
                                        window.location.href = `${globalMethods.getLocationOrigin()}${CLO_PATH}?affairId=${affairId}&chooseSplit=yes&subState=1&method=newColl&summaryId=${summaryId}&from=waitSend`;
                                      }
                                    });
                                    break;
                            }
                        },
                        () => {
                            globalMethods.message.error($.i18n('collaboration.common.to.send.failed'));
                        }
                    )
                  .finally(() => {
                    resolve();
                  });
            }else {
                resolve();
            }
        })
  });
}

export default () =>
  new Promise((resolve, reject) => {
    saveDraft(resolve, reject);
  });
